package com.meringer.beans.ejb;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.meringer.entities.Car;
import com.meringer.entities.User;
import com.meringer.utils.CarAndModel;

@Stateless
@LocalBean
public class CarEJB {
	@EJB
	UserEJB userEJB;
	@PersistenceContext
	private EntityManager em;
    public CarEJB() {
     
    }
    public  List<CarAndModel> getCars(){
    	List<Car> cars = userEJB.currentUser().getCars();
    	List<CarAndModel> camL = new ArrayList<CarAndModel>();
    	CarAndModel cam;
    	for(Car car : cars){
    		cam = new CarAndModel(car, car.getModel());
    		camL.add(cam);
    	}
    	return camL;
    }
    public int cellCar(Car car){
    	User currentUser = userEJB.currentUser();
    	List<Car> cars = currentUser.getCars();
    	cars.remove(car);
    	currentUser.setCars(cars);
    	currentUser.setBudget(currentUser.getBudget() + car.getPrice());
    	if(currentUser.getMainCar().getCarID() == car.getCarID())
    		if(cars.size() > 0)
    			currentUser.setMainCar(cars.get(0));
    	em.merge(currentUser);
    	car.setOwner(null);
    	em.merge(car);
    	return car.getPrice();
    }

}
